package com.elem.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*") // 拦截所有请求，进行编码
public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 设置编码。只有post请求才需要设置编码，get请求不需要设置
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 判断当前的请求是否post请求
        String method = request.getMethod(); // 获取请求方式
        if ("POST".equalsIgnoreCase(method)) {
            request.setCharacterEncoding("UTF-8");
        }


        // 告诉浏览器，响应的格式是：json格式以及编码格式
//        response.setContentType("text/html");
        // 必须要设置。如果不设置，前端将解析不出后台传递的数据。
        response.setContentType("application/json;charset=UTF-8");

        // 放行
        filterChain.doFilter(request, response);


    }

    @Override
    public void destroy() {

    }
}
